<template>
	<view class="content">
		<view class="bgColor">
			<image src="/static/mine/xskbBg.jpg" mode=""></image>
		</view>
		<cusHeaderVue titleContent="销售看板" :showBack="true"></cusHeaderVue>
		<view class="header" :style="{paddingTop: `calc(${scrollerHeight} + 90rpx)`}">
			<view class="headerTop">
				<view class="headerLeft">
					共负责门店<text>{{ boardData.totalShop || 0 }}</text>家
				</view>
				<view class="headerTime" @click="showMonthPicker">
					<view class="headerTimeName">
						{{ currentMonth }}
					</view>
					<u-icon name="arrow-down-fill" color="#222222" size="10"></u-icon>
				</view>
			</view>
			<view class="headerBottom">
				<view class="headerBottomLeft">
					<view class="headerBottomName">
						目标(元)
					</view>
					<view class="headerBottomNum">
						{{ formatNumber(boardData.targetAmount || 0) }}
					</view>
				</view>
				<view class="headerBottomCenter">
					<view class="headerBottomCenterTop">
						<view class="headerBottomCenterTopText">
							{{ boardData.completionRate || 0 }}<text>%</text>
						</view>
					</view>
					<view class="headerBottomCenterName">
						完成率
					</view>
				</view>
				<view class="headerBottomRight">
					<view class="headerBottomName">
						销售(元)
					</view>
					<view class="headerBottomNum">
						{{ formatNumber(boardData.actualAmount || 0) }}
					</view>
				</view>
			</view>
		</view>
		<view class="">
			<scroll-view scroll-y="true"
				:style="{height: swiperHeight}">
				<view class="listBox">
					<view v-if="loading" class="loadingBox">
						<text>加载中...</text>
					</view>
					<view v-else-if="boardData.shopList && boardData.shopList.length > 0" class="listContent">
						<view class="listLi" v-for="(item, index) in boardData.shopList" :key="index" @click="toUrl(`/pages/mine/shopXq?id=${item.id}`)">
							<view class="listName">
								{{ item.name || '未知门店' }}
							</view>
							<view class="listBottom">
								<view class="listIcon">
									<view class="listTag">
										进
									</view>
									<view class="listNum">
										￥<text>{{ formatNumber(item.stockInAmount || 0) }}</text>
									</view>
								</view>
								<view class="listIcon">
									<view class="listTag listTagX">
										销
									</view>
									<view class="listNum">
										￥<text>{{ formatNumber(item.salesAmount || 0) }}</text>
									</view>
								</view>
								<view class="listIcon">
									<view class="listTag listTagC">
										存
									</view>
									<view class="listNum">
										￥<text>{{ formatNumber(item.stockAmount || 0) }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view v-else class="emptyBox">
						<text>暂无数据</text>
					</view>
				</view>
			</scroll-view>
		</view>
		<MonthPickerPopup 
			ref="monthPickerRef" 
			@confirm="onMonthConfirm" 
			@cancel="onMonthCancel" 
		/>
	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app';
	import {
		ref,
		onMounted
	} from 'vue';
	import cusHeaderVue from '@/components/cus-header.vue';
	import MonthPickerPopup from '@/components/MonthPickerPopup.vue';
	import { GETSalesBoard } from '@/api/interface.js';
	const scrollerHeight = ref('');
	const swiperHeight = ref('');
	const currentMonth = ref('');
	const monthPickerRef = ref(null);
	const loading = ref(false);
	const boardData = ref({
		totalShop: 0,
		targetAmount: 0,
		actualAmount: 0,
		completionRate: 0,
		shopList: []
	});
	
	// 获取当前月份
	const getCurrentMonth = () => {
		const date = new Date();
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		currentMonth.value = `${year}年${month}月`;
		return `${year}-${month.toString().padStart(2, '0')}`;
	};
	
	// 格式化数字为千分位
	const formatNumber = (num) => {
		if (typeof num !== 'number') return '0';
		return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
	};
	
	// 显示月份选择器
	const showMonthPicker = () => {
		if (monthPickerRef.value) {
			monthPickerRef.value.open();
		}
	};
	
	// 月份选择确认
	const onMonthConfirm = (month) => {
		currentMonth.value = month;
		getSalesBoardData();
	};
	
	// 月份选择取消
	const onMonthCancel = () => {
		// 取消选择，不做任何操作
	};
	
	// 获取销售看板数据
	const getSalesBoardData = async () => {
		try {
			loading.value = true;
			// 解析月份字符串为年月格式
			const monthStr = currentMonth.value;
			let dateStr = '';
			if (monthStr) {
				const match = monthStr.match(/(\d+)年(\d+)月/);
				if (match) {
					dateStr = `${match[1]}-${parseInt(match[2]).toString().padStart(2, '0')}`;
				}
			}
			
			const res = await GETSalesBoard({ dateStr });
			
			if (res.code === 0 && res.data) {
				// 根据实际API返回数据格式映射字段
				const salesData = res.data;
				// 解析完成率百分比
				let completionRate = 0;
				if (salesData.wcl && typeof salesData.wcl === 'string') {
					completionRate = parseFloat(salesData.wcl.replace('%', '')) || 0;
				}
				
				boardData.value = {
					totalShop: salesData.shopNum || 0,
					targetAmount: parseFloat(salesData.plannedSales) || 0,
					actualAmount: parseFloat(salesData.sumTotalSaleMoney) || 0,
					completionRate: completionRate,
					shopList: (salesData.shopDOS || []).map(shop => ({
						id: shop.id,
						name: shop.name || '未知门店',
						stockInAmount: parseFloat(shop.totalPurchaseMoney) || 0, // 进货金额
						salesAmount: parseFloat(shop.totalSaleMoney) || 0, // 销售金额
						stockAmount: parseFloat(shop.totalStockMoney) || 0 // 库存金额
					}))
				};
			} else {
				uni.showToast({
					title: res.message || '获取数据失败',
					icon: 'none'
				});
			}
		} catch (error) {
			uni.showToast({
				title: '网络错误，请稍后重试',
				icon: 'none'
			});
			console.error('获取销售看板数据失败:', error);
		} finally {
			loading.value = false;
		}
	};
	
	//获取状态栏高度
	const getBarHeight = () => {
		uni.getSystemInfo({
			success: function(res) {
				scrollerHeight.value = res.statusBarHeight + 'px'
				const query = uni.createSelectorQuery();
				query.select('.listBox').boundingClientRect(); //.swiper是swiper类名，获取当前swiper距离顶部的位置
				query.exec(ress => {
					console.log(ress,'ress')
					swiperHeight.value = res.windowHeight - ress[0].top - res.safeAreaInsets.bottom  - 90+
					'px'; //屏幕的高度减去当前swiper距离顶部的高度就是剩余屏幕的高度 然后动态赋值给swiper
				});
			}
		});
	};
	
	const toUrl = (urlSrc) => {
		uni.navigateTo({
			url: urlSrc
		})
	};
	
	onLoad(() => {
		getBarHeight();
		getCurrentMonth();
		// 延迟调用，确保页面元素已渲染完成
		setTimeout(() => {
			getSalesBoardData();
		}, 100);
	});
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
	}

	.bgColor {
		width: 100%;
		height: 100vh;
		position: absolute;
		z-index: -1;
		top: 0;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.header {
		padding: 0 23rpx 0 42rpx;
		box-sizing: border-box;

		.headerTop {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.headerLeft {
				font-size: 27.44rpx;
				font-weight: 400;
				color: #1C2027;

				text {
					font-size: 44.87rpx;
					font-weight: 400;
					color: #F79F31;

				}
			}

			.headerTime {
				border-radius: 10.26rpx 10.26rpx 10.26rpx 10.26rpx;
				background: #ffffff99;
				padding: 15rpx 17rpx;
				box-sizing: border-box;
				display: flex;
				align-items: center;

				.headerTimeName {
					color: #222222;
					font-weight: 400;
					font-size: 25.64rpx;
					margin-right: 21rpx;
				}
			}
		}

		.headerBottom {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 13rpx;

			.headerBottomLeft {
				width: 249.92rpx;
				height: 126.28rpx;
				border-radius: 0 12.82rpx 12.82rpx 0;
				// background: #ffffff63;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				background: url('/static/mine/wcmb.png') no-repeat center;
				background-size: 100% 100%;

				.headerBottomName {
					font-size: 24.36rpx;
					font-weight: 400;
					color: #7F8494;
				}

				.headerBottomNum {
					font-size: 37.18rpx;
					font-weight: 400;
					color: #222222;
				}
			}

			.headerBottomCenter {
				.headerBottomCenterTop {
					width: 194rpx;
					height: 178rpx;
					background: url('/static/mine/cl.png') no-repeat center;
					display: flex;
					align-items: center;
					justify-content: center;
					background-size: 100% 100%;

					.headerBottomCenterTopText {
						font-size: 65.36rpx;
						font-weight: 400;
						color: #FFA62C; // 使用直接的颜色设置，确保在所有设备上都能正常显示
						margin-top: 20rpx;

						text {
							font-size: 37.18rpx;
							font-weight: 400;
							color: #FFA62C;
						}
					}


				}

				.headerBottomCenterName {
					font-size: 24.36rpx;
					font-weight: 400;
					color: #7F8494;
					text-align: center;
				}
			}

			.headerBottomRight {
				width: 249.92rpx;
				height: 126.28rpx;
				border-radius: 0 12.82rpx 12.82rpx 0;
				// background: #ffffff63;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				background: url('/static/mine/wcxs.png') no-repeat center;
				background-size: 100% 100%;

				.headerBottomName {
					font-size: 24.36rpx;
					font-weight: 400;
					color: #7F8494;
				}

				.headerBottomNum {
					font-size: 37.18rpx;
					font-weight: 400;
					color: #222222;
				}
			}
		}
	}
	.listBox{
		padding: 22rpx;
		box-sizing: border-box;
		
		.loadingBox, .emptyBox {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 80rpx 0;
			color: #999999;
			font-size: 28rpx;
		}
		
		.listLi{
			width: 100%;
			border-radius: 12.82rpx 12.82rpx 12.82rpx 12.82rpx;
			background: #ffffff;
			padding: 37rpx 26rpx;
			box-sizing: border-box;
			margin-bottom: 21rpx;
			
			&:active {
				background-color: #f8f8f8;
			}
			
			.listName{
				font-weight: 500;
				font-size: 32.05rpx;
				color: #1C2027;
				word-break: break-all;
				line-height: 44rpx;
			}
			.listBottom{
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-top: 32rpx;
				.listIcon{
					display: flex;
					align-items: center;
					.listTag{
						width: 33rpx;
						height: 33rpx;
						border-radius: 6.41rpx 6.41rpx 6.41rpx 6.41rpx;
						background: linear-gradient(0deg, #feb500,#ffcc4f);
						font-size: 23.08rpx;
						font-weight: 400;
						color: #FFFFFF;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-right: 10rpx;
					}
					.listNum{
						font-size: 24.36rpx;
						font-weight: 400;
						color: #8B8B8B;
						text{
							font-size: 33.33rpx;
							font-weight: 400;
							color: #8B8B8B;
						}
					}
					
					.listTagX{
						background: linear-gradient(0deg, #36abfb,#6acbff);
					}
					.listTagC{
						background: linear-gradient(0deg, #ff565a,#ff9292);
					}
				}
			}
		}
	}
</style>